package core

import (
	"context"
	influxdb2 "github.com/influxdata/influxdb-client-go/v2"
	"github.com/influxdata/influxdb-client-go/v2/api"
	"sync"
	"uss-root/utils"
)

var influx *Influx
var influxOnce sync.Once

type Influx struct {
	Client   *influxdb2.Client
	WriteApi api.WriteAPI
}

func NewInfluxClient() *Influx {
	influxOnce.Do(func() {
		const token = "2RqGhalscEj4uWaN82lsevCRx1otXAx1ql_gkMtu3kGjCtVYZAReca_SjtgbteB9NXqfxxXdaTz0QHopgS0wWw=="
		const bucket = "test"
		const org = "me"

		InfluxClient := influxdb2.NewClient("http://47.96.67.176:8086", token)
		influx = &Influx{
			Client:   &InfluxClient,
			WriteApi: InfluxClient.WriteAPI(org, bucket),
		}
	})
	return influx
}

func (self Influx) Write(msg string) {
	self.WriteApi.WriteRecord(msg)
	self.WriteApi.Flush()
}

func (self Influx) WriteSysData(system *SystemState) {
	//msg:=fmt.Sprintf("unit=temperature,avg=%f,max=%f", 23.5, 45.0)
	//msg,err:=json.Marshal(system)
	//if err != nil {
	//	utils.Logger.Err(err)
	//}
	self.Write(system.TagParse())
}

func (self Influx) WriteSysStream(ctx context.Context, systemStream chan *SystemState) {
	for {
		select {
		case <-ctx.Done():
			utils.Logger.Info().Msg("WriteSysStream Done")
			return
		case sys := <-systemStream:
			//utils.Println(sys)
			self.WriteSysData(sys)
		}
	}
}
